package com.zhizhi.config;


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zhizhi.common.constant.BaseEntityFieldConstant;
import com.zhizhi.util.DateUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 注入公共字段自动填充,任选注入方式即可
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    protected final static Logger logger = LoggerFactory.getLogger(MyMetaObjectHandler.class);

    @Override
    public void insertFill(MetaObject metaObject) {
        logger.info("新增公共字段");
        //此处是实体类字段名称
        //String userIdStr = ExecutionContext.getUserId();
//        Integer userId = null;
//        if (StringUtils.isNotBlank(userIdStr)) {
//            userId = Integer.valueOf(userIdStr);
//        }
        if (getFieldValByName(BaseEntityFieldConstant.CREATE_TIME, metaObject) == null) {
            //有值 不填充 无值才填充
            this.setInsertFieldValByName(BaseEntityFieldConstant.CREATE_TIME, DateUtil.localDateTimeToString(LocalDateTime.now(), DateUtil.DATE_PATTERN_yyyy_MM_dd_HH_MM_ss), metaObject);
        }

        if (getFieldValByName(BaseEntityFieldConstant.UPDATE_TIME, metaObject) == null) {
            //有值 不填充 无值才填充
            this.setInsertFieldValByName(BaseEntityFieldConstant.UPDATE_TIME, DateUtil.localDateTimeToString(LocalDateTime.now(), DateUtil.DATE_PATTERN_yyyy_MM_dd_HH_MM_ss), metaObject);
        }

//        if (getFieldValByName(BaseEntityFieldConstant.CREATE_USER, metaObject) == null) {
//            //有值 不填充 无值才填充
//            this.setInsertFieldValByName(BaseEntityFieldConstant.CREATE_USER, userId, metaObject);
//        }


//        if (getFieldValByName(BaseEntityFieldConstant.UPDATE_USER, metaObject) == null) {
//            //有值 不填充 无值才填充
//            this.setInsertFieldValByName(BaseEntityFieldConstant.UPDATE_USER, userId, metaObject);
//        }


    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //此处是实体类字段名称
        logger.info("更新公共字段");
        //此处是实体类字段名称
//        String userIdStr = ExecutionContext.getUserId();
//        Integer userId = null;
//        if (StringUtils.isNotBlank(userIdStr)) {
//            userId = Integer.valueOf(userIdStr);
//        }
        this.setInsertFieldValByName(BaseEntityFieldConstant.UPDATE_TIME, DateUtil.localDateTimeToString(LocalDateTime.now(), DateUtil.DATE_PATTERN_yyyy_MM_dd_HH_MM_ss), metaObject);

        //  this.setInsertFieldValByName(BaseEntityFieldConstant.UPDATE_USER, userId, metaObject);


    }

}